
import weexHttp from "@/_js/https"; ;
const weexFunction = weex.requireModule("WeexFunction");

import modal from "@/_js/modal";
import API from "@/_js/api";

var I18N = {};
I18N.en = {
  "终止成功":"Successful termination",
  "本地未找到 &{1} API, 或该API已过期,无法完成操作":"The local & {1} API was not found, or it has expired and cannot complete the operation",
};
I18N.ja = {
  "终止成功":"终止成功",
  "本地未找到 &{1} API, 或该API已过期,无法完成操作":"本地未找到 &{1} API, 或该API已过期,无法完成操作",
};

I18N.ko = {
  "终止成功":"终止成功",
  "本地未找到 &{1} API, 或该API已过期,无法完成操作":"本地未找到 &{1} API, 或该API已过期,无法完成操作",
};

var language = weex.config.language;
// var language = "en";
var msg = I18N[language];
if(!msg){
  msg = {};
}
var T = function(text){
    return msg[text] || text;
};
export default {
  /******************************************* 普通方法*/
  /** 重启
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  restart(param, success=()=>{}, failure=()=>{}){

    var keys = ['executeId'];
    if (this.checkParam(param, keys, true)) return;
    this.httpRestart(param, success, failure);
  },

  /** 参数修改
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {SUSPEND已暂停} states
   * 
   * @param {参数对象} reserves 
   * @param {其他设置} setMap 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  modifyParam(param, success=()=>{}, failure=()=>{}) {
    
    var keys = ['executeId','executeConfig', 'states',
                'reserves', 'setMap'];
    if (this.checkParam(param, keys, true)) return;

    this.httpEditConfig(param, success, failure);
  },

  /** 加仓
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {SUSPEND已暂停} states
   * 
   * @param {投资数量} investCoinnNum 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  addInvest(param, success=()=>{}, failure=()=>{}){

    var keys = ['executeId','executeConfig', 'states',
                'investCoinnNum'];
    if (this.checkParam(param, keys, true)) return;

    var _success = ()=>{
      var pair = param.executeConfig.tradePairs[0];
      pair.apiId.length&&API.addApiStrategy(pair.apiId, 'USDT', '0');
      success();
    }
    
    this.httpEditConfig(param, _success, failure);
  },

  /** 重启-多币对
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {子策略数组} sonExexuteIds
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  restarts(param, success=()=>{}, failure=()=>{}){

    var keys = ['executeId','sonExexuteIds'];
    if (this.checkParam(param, keys, true)) return;
    this.httpRestarts(param, success, failure);
  },

  /** 参数修改-多币对
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {SUSPEND已暂停} states
   * @param {子策略数组} sonExexuteIds
   * 
   * @param {参数对象} reserves 
   * @param {其他设置} setMap 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  modifyParams(param, success=()=>{}, failure=()=>{}) {
    
    var keys = ['executeId','executeConfig', 'states', 'sonExexuteIds',
                'reserves', 'setMap'];
    if (this.checkParam(param, keys, true)) return;

    this.httpEditConfigs(param, success, failure);
  },

  /** 加仓-多币对
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {SUSPEND已暂停} states
   * @param {子策略数组} sonExexuteIds
   * 
   * @param {投资数量} investCoinnNum 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  addInvests(param, success=()=>{}, failure=()=>{}){

    var keys = ['executeId','executeConfig', 'states',  'sonExexuteIds',
                'investCoinnNum'];
    if (this.checkParam(param, keys, true)) return;

    var _success = ()=>{
      var pair = param.executeConfig.tradePairs[0];
      pair.apiId.length&&API.addApiStrategy(pair.apiId, 'USDT', '0');
      success();
    }

    this.httpEditConfigs(param, _success, failure);
  },

  /******************************************* 辅助方法*/
  /** 校验参数
   * 
   * @param {参数} param 
   * @param {参数关键字数组} keys 
   * @param {turn弹出Load} hud
   */
  checkParam(param, keys, hud){
    hud&&modal.showLoad();
    for (let index = 0; index < keys.length; index++) {
      var key = keys[index];
      if (param[key] == null) {
        hud&&modal.hideLoad();
        modal.toast('缺失：'+key);
        return true;
      }
    }
    return false;
  },

  /** 校验API
   * 
   * @param {apiId} apiId 
   * @param {Ap名称} apiName 
   */
  checkApi(apiId, apiName, success=()=>{}, failure=()=>{}){
    
    API.getApi(apiId, 'YES', (api)=>{
      if (apiId.length > 0 && api == null) {
        modal.toast(T('本地未找到 &{1} API, 或该API已过期,无法完成操作').replace('&{1}',apiName));
        failure&&failure();
        return;
      } else {
        success&&success(api);
      }
    });
  },

  /** 获取Api参数
   * 
   * @param {api} api 
   * @param {*} success 成功回调
   */
  getApiParam(api, success=(apiMap)=>{}){

    if (api == null) { 
      success({});
      return;
    }
    
    if (api.apiId == null || api.apiId.length == 0) {
      var apiMap = {'isMimic':true, 'apiName':api.exchangeName, 'apiId':'', 'api':''};
      success(apiMap);
      return;
    }
    
    this.httpPublicKey(api.apiId, (key)=>{
      API.rsaApi(api, key, (rsa)=>{
        var apiMap = {'isMimic':false, 'apiName':api.apiName, 'apiId':api.apiId, 'api':rsa};
        success(apiMap);
      });
    });
  },

  /** 获取执行参数
   * 
   * @param {参数} param 
   * @param {api参数} apiMap 
   */
  getExecuteConfig(param, apiMap){
    
    //交易对数据
    var pairMap = {};
    if (param.pairMap) {
      pairMap = param.pairMap;
      var pairKeys = ['last', 'usdPrice', 'baseCoinUsdPrice' ,'increase'];
      for (let index = 0; index < pairKeys.length; index++) {
        var key = pairKeys[index];
        delete pairMap[key];
      }
      pairMap['exchange'] = pairMap.exchangeName;
    }

    //投入数据
    var investMap = {};
    if (param.buyFee) {
      investMap['buyFee'] = param.buyFee;
      investMap['soldFee'] = param.buyFee;
    }
    if (param.investCoin) investMap['investCoin'] = param.investCoin;
    if (param.investCoinnNum) {
      investMap['investCoinnNum'] = param.investCoinnNum;
      investMap['counterCoinAmount'] = param.investType ? param.investCoinnNum : '0';
      investMap['baseCoinAmount'] = param.investType ?  '0' : param.investCoinnNum;
    }

    //执行配置-交易对、参数数组、其他设置、多币对
    var executeConfig = param.executeConfig;
    var tradePair = executeConfig['tradePairs'][0];
    tradePair = Object.assign(tradePair, apiMap);
    tradePair = Object.assign(tradePair, pairMap);
    tradePair = Object.assign(tradePair, investMap);
    if (param.signal) executeConfig['signal'] =  param.signal;
    if (param.reserves) executeConfig['reserves'] =  param.reserves;
    if (param.setMap) executeConfig = Object.assign(executeConfig, param.setMap);
    if (param.pairs) {
      var newPairs = [{'counterCoin':pairMap.counterCoin, 'baseCoin':pairMap.baseCoin}];
      for (let index = 0; index < param.pairs.length; index++) {
        var newPair = param.pairs[index];
        newPairs.push({'counterCoin':newPair.counterCoin, 'baseCoin':newPair.baseCoin});
      }
      executeConfig['pairs'] =  newPairs; 
    }

    return executeConfig;
  },

  //显示服务器列表
  showServers(isPrivate, api, back) {
    if (!api) {
      back();
      return;
    }

    this.httpMyServers((datas)=>{

        var array = [];
        var dict = {};
        for (let index = 0; index < datas.length; index++) {
          var item = datas[index];
          if (item.serverStatus == 'ARRANGING') {
            continue;
          }
          
          item.name = item.serverName + '#' + (item.serverMark ? item.serverMark : item.serverCode);
          if (!isPrivate || item.serverType == 'PRIVATE') {
            dict[item.name] = item;
            array.push(item.name);
          }
        }

        if (!array.length) {

          var parm = {title:T("提示"),
                  message:isPrivate ? T("暂无独享服务器，请先购买独享服务器。") : T("暂无服务器，开通会员赠送服务器。"),
                  okBtn:T("前往"), cancelBtn:T("取消")};
          modal.confirm(parm, (bool)=>{
            if (bool == "true") {
              isPrivate 
              ? navigator.open('', "server/Server", {}, {'navColor':'#040448'}) 
              : navigator.open('', "mine/Vip", {}, {'navColor':'#1677fe'});
            }
          });
        }

      modal.actionSheet(array, '', (value)=>{
        var server = dict[value];
        back && back(server);
      });
    });
  },

  /******************************************* http*/
  /** HTTP 获取执行服务器公钥
   * 
   * @param {String} apiId 获取服务器公钥
   * @param {*} success 成功回调
   */
  httpPublicKey(apiId, success=(key)=>{}){

    if (apiId == null || apiId.length == 0) {
      success('');
      return;
    }

    var param = {serverType:'strategy'};
    weexHttp.post("assetsV2/getPublicKey",param,true,(data)=>{
      
      if(data.status == 200){
        var key = data.data.publicKey;
        success&&success(key);
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  /** HTTP 暂停
   * @param {执行id} executeId 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpStip(executeId, isMany, success=()=>{}){
    modal.showLoad();
    var param = {executeId:executeId};

    var url = isMany ? 'strategyV3/manyStrategySuspend' : 'strategyV3/strategySuspend';
    weexHttp.postX(url,param,true,(data)=>{
      modal.hideLoad();
      if(data.status == 200){
        success&&success();
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  /** HTTP 终止
   * @param {执行id} executeId 
   * @param {是否测单} cancelOrder 
   * @param {是否兑换} isConvert 
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpEnd(param, success=()=>{}, failure=()=>{}){

    var keys = ['executeId', 'cancelOrder', 'isConvert', 'apiId', 'isMany'];
    if (this.checkParam(param, keys, true)) return;

    var url = param.isMany ? 'strategyV3/manyStrategyEnd' : 'strategyV3/strategyEnd';
    weexHttp.postX(url,param,true,(data)=>{
      if(data.status == 200){
        
        var ok = ()=>{
          modal.hideLoad();
          modal.toast(T('终止成功'));
          success&&success();
        };
        if (param.apiId.length) {
          API.synchroApi(param.apiId, ok, ok)
        } else {
          ok();
        }
      } else {
        modal.hideLoad();
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  /** HTTP 重启
   * 
   * @param {手续费} buyFee 
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * 
   * @param {投资数量} investCoinnNum 
   * 
   * @param {参数对象} reserves 
   * @param {其他设置对象} setMap
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpRestart(param ,success=()=>{}, failure=()=>{}){

    var paramMap = {'executeId':param.executeId+''};
    if (param.serverCode) {
      paramMap['serverCode'] = param.serverCode;
    }
    weexHttp.postX("strategyV3/strategyRestart",paramMap,true,(data)=>{
      modal.hideLoad();
      if(data.status == 200){
        success&&success();
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  /** HTTP 编辑参数
   * 
   * @param {手续费} buyFee 
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * 
   * @param {投资数量} investCoinnNum 
   * 
   * @param {参数对象} reserves 
   * @param {其他设置对象} setMap
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpEditConfig(param ,success=()=>{}, failure=()=>{}){

    var executeConfig = this.getExecuteConfig(param, {});
    var paramMap = {'executeId':param.executeId+'', 
                    'executeConfig':JSON.stringify(executeConfig)};
    
    weexHttp.postX("strategyV3/editExecuteConfig",paramMap,true,(data)=>{
      modal.hideLoad();
      if(data.status == 200){
        success&&success();
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  /** HTTP 重启-多币对
   * 
   * @param {手续费} buyFee 
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {子策略数组} sonExexuteIds
   * 
   * @param {投资数量} investCoinnNum 
   * 
   * @param {参数对象} reserves 
   * @param {其他设置对象} setMap
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpRestarts(param ,success=()=>{}, failure=()=>{}){

    var paramMap = {'executeId':param.executeId+'',
                    'sonExexuteIds':param.sonExexuteIds};
    if (param.serverCode) {
      paramMap['serverCode'] = param.serverCode;
    }

    weexHttp.postX("strategyV3/manyStrategyRestart",paramMap,true,(data)=>{
      modal.hideLoad();
      if(data.status == 200){
        success&&success();
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  /** HTTP 编辑参数 -多币对
   * 
   * @param {手续费} buyFee 
   * 
   * @param {执行Id} executeId 
   * @param {执行配置} executeConfig 
   * @param {子策略数组} sonExexuteIds
   * 
   * @param {投资数量} investCoinnNum 
   * 
   * @param {参数对象} reserves 
   * @param {其他设置对象} setMap
   * 
   * @param {成功回调} success 
   * @param {失败回调} failure 
   */
  httpEditConfigs(param ,success=()=>{}, failure=()=>{}){

    var executeConfig = this.getExecuteConfig(param, {});
    var paramMap = {'executeId':param.executeId+'', 
                    'executeConfig':JSON.stringify(executeConfig),
                    'sonExexuteIds':param.sonExexuteIds};

    weexHttp.postX("strategyV3/manyEditExecuteConfig",paramMap,true,(data)=>{
      modal.hideLoad();
      if(data.status == 200){
        success&&success();
      } else {
        modal.toast(data.msg);
        failure&&failure();
      }
    });
  },

  //我的服务器列表
  httpMyServers(success) {

    modal.showLoad();
    var param = {};
    weexHttp.post("server/queryMyServerList",param,true,(data) => {
        modal.hideLoad();
        if (data.status == 200) {
          var datas = data.data;
          success&&success(datas);
        } else {
          modal.toast(data.msg);
        }
      }
    );
  },
}
  